package com.free.mini.gateway.exceptions;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;

import com.free.mini.common.base.ResultData;
import com.free.mini.gateway.constants.GatewayConstant;
import com.free.mini.gateway.filter.GatewayContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class GateWayExceptionHandlerAdvice {

    @SuppressWarnings("rawtypes")
    @ExceptionHandler(value = {Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData handle(ServerRequest request, Throwable throwable) {
        ServerWebExchange exchange = request.exchange();
        ResultData resultData = ResultData.error();

        GatewayContext gatewayContext = (GatewayContext) exchange.getAttributes()
                .get(GatewayConstant.CACHE_GATEWAY_CONTEXT);
        if (gatewayContext == null) {
            gatewayContext = new GatewayContext(exchange);
        }
        gatewayContext.setResult(resultData);

        log.error(throwable.getMessage());
        throwable.printStackTrace();
        return resultData;
    }
}